﻿from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse
from django.shortcuts import redirect
import requests


from django.db.models import Q

#from django.core.files.base import ContentFile
#from django.core.files.storage import default_storage
from django.conf import settings
import random
import os
import json
import datetime
import time
import uuid
import base64
import xlrd

from django.core.mail import send_mail
from uploadimg.upload_qiniu import upload_img
from index.models import Mapuser,Editer,Mfile
from index.models import Game,Map,Group,Category,Point,Region
from index.models import Icon,Iconclass
from index.models import Todocategory,Todo,Checklist,Check


#用于测试占位的固定json返回
def test_return(request):
    return JsonResponse({"code":0,"data":"nothing"})

#'127.0.0.1:8000/user/getVcode'  普通用户根据邮箱获取验证码
def mail_code(request):
    """发送消息内容到邮箱"""
    temcode = str(random.randint(100000,999999))
    data = json.loads(request.body)
    print(data)
    print(temcode)
    if Editer.objects.filter(mail=data["email"]).count():    #是管理员
        tem = Editer.objects.filter(mail=data["email"])
        tem.update(vcode=temcode)
    elif Mapuser.objects.filter(mail=data["email"]).count():   #旧用户
        tem = Mapuser.objects.filter(mail=data["email"])
        tem.update(vcode=temcode)
    else:                                                    #新用户
        print(1)
        temnum = Mapuser.objects.all().count()
        temid = Mapuser.objects.all()[temnum-1].uid + 1
        Mapuser.objects.create(uid=temid, mail=data["email"],username="用户%d" % (temid),vcode=temcode)
        stok = str(uuid.uuid4())     #存储形式 新用户存一个类token   这里可省？
        Mfile.objects.create(uid=temid,token=stok)
    # 发送邮件
    send_mail(subject = "地图登录验证",
              message = "验证码是"+temcode,
              from_email = settings.EMAIL_FROM,
              recipient_list = [data["email"]],
              )
    return JsonResponse({"code":0,"msg":"邮件已发送"})

#'127.0.0.1:8000/user/login'  邮箱登录，用户或管理员
def login(request):
    data = json.loads(request.body)
    if Editer.objects.filter(mail=data["email"]).count():  # 是管理员
        tem = Editer.objects.get(mail=data["email"])
        stok = str(uuid.uuid4())
        tem.token = stok
        tem.save()
        if tem.vcode == data["vCode"]:
            tem.vcode = '101010'
            tem.save()
            return JsonResponse({"code":0,"data":{"session_token":str(base64.b64encode(stok.encode()))[2:50],"file":[],"list":{},"role":"editer"}})
        else:
            return JsonResponse({"code": 1, "msg": "验证码错误"})
    elif Mapuser.objects.filter(mail=data["email"]).count():                           #是普通用户
        tem = Mapuser.objects.get(mail=data["email"])
        stok = str(uuid.uuid4())  # 存储形式
        temt = Mfile.objects.get(uid = tem.uid)
        temt.token = stok
        temt.save()
        if tem.vcode == data["vCode"]:
            tem.vcode='101010'
            tem.save()
            return JsonResponse({"code":0,"data":{"session_token":str(base64.b64encode(stok.encode()))[2:50],"lastModify":temt.ltime,"file":eval(temt.mdfile),"list":eval(temt.chlist),"role":"user"}})
        else :
            return JsonResponse({"code":1,"msg":"验证码错误"})
    else:
        return JsonResponse({"code": 1, "msg": "验证码错误"})

#'127.0.0.1:8000/user/logout'  普通用户登出
def logout(request):
    return JsonResponse({"code":0,"msg":"已成功退出"})

#'127.0.0.1:8000/user/verifyToken'  判断token是否过期
def post_token(request):
    get_token=request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if Editer.objects.filter(token=stok).count():       #是管理员
        return JsonResponse({"code": 0,"data": {"session_token": get_token,"file":[],"list":{},"role":"editer"}})
    elif Mfile.objects.filter(token = stok).count():
        tema=Mfile.objects.get(token = stok)
        return JsonResponse({"code":0,"data":{"session_token":get_token,"lastModify":tema.ltime,"file":eval(tema.mdfile),"list":eval(tema.chlist),"role":"user"}})
    else:
        return JsonResponse({"code":1,"msg":"登录过期，请重新登录"})

#'127.0.0.1:8000/user/markPoint'      标记点
def markpoint(request):
    get_token = request.META.get('HTTP_X_TOKEN')
    stok = base64.b64decode(get_token).decode()
    tem=Mfile.objects.get(token=stok)
    temdata=json.loads(request.body)
    temjson=eval(tem.mdfile)
    if temdata["value"]:
        temjson[str(temdata["id"])] = 1
        tem.mdfile = json.dumps(temjson)
        tem.ltime = temdata["modifyTime"]
        tem.save()
    elif str(temdata["id"]) in temjson:
        temjson.pop(str(temdata["id"]))
        tem.mdfile = json.dumps(temjson)
        tem.ltime = temdata["modifyTime"]
        tem.save()
    return JsonResponse({"code":0,"msg":"操作成功"})

#'127.0.0.1:8000/third/login'   第三方登录
def third_login(request):
    print('000', request.GET.get('route'), '000')
    global list_url
    list_url = request.GET.get('route').split('?')
    print(list_url)
    client_id = '3c3625e596b36b58b2ae1fea02cdd03eb147ddc0f465b9456f5a60f6328d3972'
    gitee_code_url = 'https://gitee.com/oauth/authorize/'
    callback_url = 'http://101.34.47.125/third/callback'              #'http://127.0.0.1:8000/third/callback'
    return  redirect(gitee_code_url+'?client_id=%s&redirect_uri=%s&response_type=code' % (client_id,callback_url))

#'127.0.0.1:8000/third/callback'  第三方登录回调
def third_callback(request):
    #通过code获取assess_token
    temcode = request.GET.get('code','')
    gitee_token_url = 'https://gitee.com/oauth/token/'
    temparams = {
        'grant_type': "authorization_code",
        'code': temcode,
        'client_id': "3c3625e596b36b58b2ae1fea02cdd03eb147ddc0f465b9456f5a60f6328d3972",
        'redirect_uri': "http://101.34.47.125/third/callback",             #'http://127.0.0.1:8000/third/callback'
        'client_secret': "719222ffa7ce8928157f7d8a961fbda9dd8d67a1ef9f49e9e811af97449f15b3"
    }
    access_token_res = requests.post(gitee_token_url, params=temparams).json()
    print(access_token_res)
    #通过token（gitee）获取用户info
    gitee_info_url = 'https://gitee.com/api/v5/user/'
    temval = {
        'access_token': access_token_res['access_token'],
    }
    info_res = requests.get(gitee_info_url,params=temval).json()
    gitee_id =info_res['id']    # type:int
    print(gitee_id)
    #开始本服务器的用户验证
    if Editer.objects.filter(giteeid=gitee_id).count():    #是管理员
        temu = Editer.objects.get(giteeid=gitee_id)
        stok = str(uuid.uuid4())  # 存储形式
        temu.token = stok
        temu.save()
        if len(list_url) == 1:   #route不带?参数
            return redirect(list_url[0]+'?session_token=%s' % (str(base64.b64encode(stok.encode()))[2:50]))
        else:                   #route带?参数
            list_val = ''
            for j in range(1,len(list_url)):
                if j != 1:
                    list_val = list_val + '&'
                list_val = list_val+list_url[j]
            return redirect(list_url[0] + '?%s' % (list_val)+'&session_token=%s' % (str(base64.b64encode(stok.encode()))[2:50]))
    elif Mapuser.objects.filter(giteeid=gitee_id).count():   #旧用户
        temu = Mapuser.objects.get(giteeid=gitee_id)
        stok = str(uuid.uuid4())  # 存储形式
        temt = Mfile.objects.get(uid=temu.uid)
        temt.token = stok
        temt.save()
        if len(list_url) == 1:   #route不带?参数
            return redirect(list_url[0]+'?session_token=%s' % (str(base64.b64encode(stok.encode()))[2:50]))
        else:                   #route带?参数
            list_val = ''
            for j in range(1,len(list_url)):
                if j != 1:
                    list_val = list_val + '&'
                list_val = list_val+list_url[j]
            return redirect(list_url[0] + '?%s' % (list_val)+'&session_token=%s' % (str(base64.b64encode(stok.encode()))[2:50]))
    else:               #新用户
        print(1)
        temnum = Mapuser.objects.all().count()
        temid = Mapuser.objects.all()[temnum - 1].uid + 1
        Mapuser.objects.create(uid=temid, username=info_res['name'],giteeid=gitee_id)     #新建一条用户
        stok = str(uuid.uuid4())  # 存储形式 新用户存一个类token
        Mfile.objects.create(uid=temid, token=stok)     #新建一条记录
        if len(list_url) == 1:  # route不带?参数
            return redirect(list_url[0] + '?session_token=%s' % (str(base64.b64encode(stok.encode()))[2:50]))
        else:  # route带?参数
            list_val = ''
            for j in range(1, len(list_url)):
                if j != 1:
                    list_val = list_val + '&'
                list_val = list_val + list_url[j]
            return redirect(list_url[0] + '?%s' % (list_val) + '&session_token=%s' % (str(base64.b64encode(stok.encode()))[2:50]))





#'127.0.0.1:8000/data/games'   获取所有游戏信息
def get_game(request):
    json_game = {"code": 0}
    temlist = []
    if not request.GET.get('gameId'):
        for i in Game.objects.all():
            temlist.append({"id": i.id, "name": i.name, "title": i.title, "img": i.img,"color":i.color,"background":i.bg_url})
    else:
        temval = int(request.GET.get('gameId'))
        for i in Game.objects.filter(id=temval):
            temlist.append({"id": i.id, "name": i.name, "title": i.title, "img": i.img,"color":i.color,"background":i.bg_url})
    json_game["data"] = {"list":temlist}
    return JsonResponse(json_game)

#'127.0.0.1:80/data/maps'  获取所有地图信息
def get_map(request):
    json_map={"code":0}
    temlist=[]
    temval = int(request.GET.get('gameId'))    #获取游戏id
    for i in Map.objects.values('id','name','title','img').filter(gid=temval):
        temlist.append(i)
    json_map["data"] = {"list":temlist}
    return JsonResponse(json_map)

#'127.0.0.1:80/data/map'      获取某个地图基础信息
def get_intomap(request):
    json_map={"code":0}
    temval = int(request.GET.get('mapId'))  #地图id
    temdata = Map.objects.get(id=temval)
    json_map["data"] = {"mapSize":[temdata.size_w,temdata.size_h],"layerUrl":temdata.layerurl,"layers":temdata.layers,"color":temdata.color}
    return JsonResponse(json_map)

#'127.0.0.1:80/data/category' 获取某个地图的所有分类信息
def get_category(request):
    json_category={"code":0}
    temval = int(request.GET.get('mapId'))  # 地图id
    temlist = []
    for i in Group.objects.filter(mid = temval,issurvival=True):
        temlist.append({"id":i.id,"name":i.name,"title":i.title,"group":[]})
        for j in Category.objects.filter(grid=i.id,issurvival=True):
            temlist[-1]["group"].append({"id":j.id,"name":j.name,"title":j.title,"iconUrl":j.iconurl,"shadowUrl":j.shadowurl,
                                         "cluster":j.cluster,"status":j.status,"count":Point.objects.filter(cid=j.id).count()})
    region_list = list(Region.objects.filter(mid=temval,issurvival=True).values('id','x','y','title'))
    json_category["data"] = {"list": temlist,"region":region_list}
    return JsonResponse(json_category)

#'127.0.0.1:80/data/points'   获取地图所有点
def get_point(request):
    mapid = int(request.GET.get('mapId'))
    nowc = Category.objects.filter(id__startswith=mapid,issurvival=True)
    listzong = []
    for i in nowc:
        listzong.append({"cid": i.id, "features": []})
        nowp = Point.objects.filter(id__startswith=i.id,issurvival=True).values('id', 'x', 'y')
        listzong[-1]["features"] = list(nowp)
    jsonzong = {"code": 0, "data": {"list": listzong}}
    return JsonResponse(jsonzong)

#'127.0.0.1：8000/data/singlepoint'   获取单个点内容
def get_singlepoint(request):
    temval = int(request.GET.get('pointId'))
    temp = Point.objects.get(id=temval)
    temdata = {"popTitle":temp.title,"popupContent":temp.content,"imgurl":temp.img}
    return JsonResponse({"code":0,"data":temdata})

#‘127.0.0.1:8000/data/point'    获取某个点的全部内容
def point_all(request):
    tempointid = int(request.GET.get('pointId'))
    tempoint = Point.objects.get(id = tempointid)
    temcategory = Category.objects.get(id = tempoint.cid)
    json_point = {"code":0}
    json_point["data"] = {"id":tempoint.id,"x":tempoint.x,"y":tempoint.y,"shadowUrl":temcategory.shadowurl,
                          "iconUrl":temcategory.iconurl,"popTitle":tempoint.title,"popupContent":tempoint.content,"imgurl":tempoint.img}
    return JsonResponse(json_point)






#‘127.0.0.1:8000/data/todos'   获取某个游戏的全部事件
def get_todo(request):
    temval = request.GET.get('gameId')
    json_todo = {"code":0}
    list_doto = list(Todo.objects.filter(gid = temval).values('id','title','classtitle','mtitle','info','pointurl'))
    json_todo["data"] = {"list":list_doto}
    return JsonResponse(json_todo)

#'127.0.0.1:8000/editer/upexcel'  上传一个excel生成检查表
def upexcel(request):

    n1 = '任务检查表1'
    n2 = '任务检查表2'
    f1 = 'E:/bbdexm\gamemap_linshi/mession1.xlsx'
    f2 = 'E:/bbdexm\gamemap_linshi/新建 Microsoft Excel 工作表.xlsx'
    wb = xlrd.open_workbook(f2)
    sh = wb.sheet_by_name('Sheet1')
    #Checklist.objects.create(id=1101, title=n2, gid=11)
    num = 11030000
    for i in range(1, sh.nrows):
        now_json = dict(zip(sh.row_values(0), sh.row_values(i)))
        now_json["id"] = num
        now_json = json.dumps(now_json, ensure_ascii=False)
        Check.objects.create(id=num, content=now_json, lid=1103)
        num += 1
    return HttpResponse('ok')
    pass

#'127.0.0.1:8000/data/checklists'  获取某个游戏检查表列表
def get_checklist(request):
    temval = request.GET.get('gameId')
    json_checklist = {"code": 0,"data":{"list":[]}}
    for i in Checklist.objects.filter(gid = temval):
        json_checklist["data"]["list"].append({"listid":i.id,"listtitle":i.title})
    return JsonResponse(json_checklist)

#'127.0.0.1:8000/data/checks'  获取某个检查表所有条目
def get_check(request):
    temval = request.GET.get('checklistId')
    json_check = {"code":0,"data":{"list":[]}}
    for i in Check.objects.filter(lid = temval):
        json_check["data"]["list"].append(eval(i.content))
    return JsonResponse(json_check)

#‘127.0.0.1:8000/user/check’   标记检查表
def markcheck(request):
    get_token = request.META.get('HTTP_X_TOKEN')
    stok = base64.b64decode(get_token).decode()
    if not Mfile.objects.filter(token=stok).count():
        return JsonResponse({"code": 0, "msg": "登录过期"})
    data = json.loads(request.body)
    tem = Mfile.objects.get(token=stok)
    s_list = data["list"]
    for i in range(len(data["list"])):
        s_list[i] = int(data["list"][i])
    print(s_list)
    print(eval(tem.chlist))
    tem.chlist = str(s_list)
    tem.save()
    return JsonResponse({"code":0,"msg":"标记成功"})







#'127.0.0.1:80/admin/addGroup' 添加大类
def post_group(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code":1,"msg":"没有权限，请登录管理员用户"})
    else:
        temdata=json.loads(request.body)
        temnum = Group.objects.filter(mid=temdata["mid"]).count()
        if temnum ==0:
            temval=temdata["mid"]*100
        else:
            temval = Group.objects.filter(mid=temdata["mid"])[temnum-1].id+1
        Group.objects.create(id=temval,name=temdata["name"],title=temdata["title"],mid=temdata["mid"])
        return JsonResponse({"code":0,"data":{"id":temval}})

#'127.0.0.1:80/admin/addCategory' 添加小类
def post_category(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temid = json.loads(request.body)["groupId"]
        temdata = json.loads(request.body)["itemObj"]
        temnum = Category.objects.filter(grid=temid).count()
        if temnum == 0:
            temval=temid*100
        else:
            temval = Category.objects.filter(grid=temid)[temnum - 1].id + 1
        print(temval)
        Category.objects.create(id=temval,name=temdata["name"],title=temdata["title"],iconurl=temdata["iconUrl"],shadowurl=temdata["shadowUrl"],cluster=temdata["cluster"],grid=temid)
        return JsonResponse({"code":0,"data":{"id":temval}})

#'127.0.0.1:80/admin/addPoint' 添加点
def post_point(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata1 = json.loads(request.body)["geometry"]
        temdata2 = json.loads(request.body)["properties"]
        temid = json.loads(request.body)["cid"]
        temnum = Point.objects.filter(cid=temid).count()
        if temnum ==0:
            temval = temid*1000
        else:
            temval = Point.objects.filter(cid=temid)[temnum - 1].id + 1
        print(temval)
        Point.objects.create(id=temval,x=temdata1["coordinates"][0],y=temdata1["coordinates"][1],
                             title=temdata2["popTitle"],content=temdata2["popupContent"],img=temdata2["imgurl"],type2=temdata1["type"],cid=temid)
        return JsonResponse({"code":0,"data":{"id":temval}})

#127.0.0.1:8000/editer/editPoint   编辑点
def editpoint(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        tempoint = Point.objects.get(id=temdata["id"])
        tempoint.title = temdata["properties"]["popTitle"]
        tempoint.content = temdata["properties"]["popupContent"]
        tempoint.img = temdata["properties"]["imgurl"]
        tempoint.save()
        return JsonResponse({"code":0,"data":{"id":tempoint.id}})

#127.0.0.1:8000/editer/movePoint   移动点
def movepoint(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        tempoint = Point.objects.get(id=temdata["id"])
        tempoint.x = temdata["coordinates"][0]
        tempoint.y = temdata["coordinates"][1]
        tempoint.save()
        return JsonResponse({"code": 0, "msg":"修改成功"})

#127.0.0.1:8000/editer/deletePoint   删除点
def deletepoint(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        tempoint = Point.objects.get(id=temdata["id"])
        tempoint.issurvival = False
        tempoint.save()
        return JsonResponse({"code":0,"msg":"删除成功"})

#127.0.0.1:8000/editer/editGroup   编辑大类
def editgroup(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        temgroup = Group.objects.get(id=temdata["id"])
        temgroup.name = temdata["name"]
        temgroup.title = temdata["title"]
        temgroup.save()
        return JsonResponse({"code":0,"msg":"编辑成功"})

#127.0.0.1:8000/editer/editCategory   编辑小类
def editcategory(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        temcate = Category.objects.get(id=temdata["id"])
        temcate.name = temdata["name"]
        temcate.title = temdata["title"]
        temcate.iconurl = temdata["iconUrl"]
        temcate.shadowurl = temdata["shadowUrl"]
        temcate.cluster = temdata["cluster"]
        temcate.save()
        return JsonResponse({"code": 0, "msg": "编辑成功"})

#127.0.0.1:8000/editer/deleteGroup   删除大类
def deletegroup(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        temgroup = Group.objects.filter(id = temdata["id"])
        temgroup.update(issurvival = False)
        temcate = Category.objects.filter(id__startswith = temdata["id"])
        temcate.update(issurvival = False)
        tempoint = Point.objects.filter(id__startswith=temdata["id"])
        tempoint.update(issurvival = False)
        return JsonResponse({"code":0,"msg":"删除成功"})

#127.0.0.1:8000/editer/deletecategory  删除小类
def deletecategory(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        temcate = Category.objects.filter(id=temdata["id"])
        temcate.update(issurvival = False)
        tempoint = Point.objects.filter(id__startswith=temdata["id"])
        tempoint.update(issurvival = False)
        return JsonResponse({"code": 0, "msg": "删除成功"})




#127.0.0.1:8000/editer/addRegion   添加一个地区
def post_region(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        temnum = Region.objects.filter(mid=temdata["mid"]).count()
        if temnum == 0:
            temid = temdata["mid"] * 100000+99000
        else:
            temid = Region.objects.filter(mid=temdata["mid"])[temnum - 1].id + 1
        Region.objects.create(id=temid,title=temdata["title"],x=temdata["x"],y=temdata["y"],mid=temdata["mid"])
        return JsonResponse({"code": 0, "data":{"id":temid}})

#127.0.0.1:8000/editer/editRegion   编辑一个地区
def editregion(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        temregion = Region.objects.get(id=temdata["id"])
        temregion.x = temdata["x"]
        temregion.y = temdata["y"]
        temregion.title = temdata["title"]
        temregion.save()
        return JsonResponse({"code":0,"msg":"修改成功"})

#127.0.0.1:8000/editer/editRegion   删除一个地区
def deleteregion(request):
    get_token = request.META.get('HTTP_X_TOKEN','')
    stok = base64.b64decode(get_token).decode()
    if not Editer.objects.filter(token=stok).count():  # 不是管理员
        return JsonResponse({"code": 1, "msg": "没有权限，请登录管理员用户"})
    else:
        temdata = json.loads(request.body)
        temregion = Region.objects.get(id=temdata["id"])
        temregion.issurvival = False
        temregion.save()
        return JsonResponse({"code": 0, "msg": "修改成功"})








#'127.0.0.1:80/admin/getIcon'    获取图标
def post_icon(request):
    json_icon = {"code":0}
    temval = int(request.GET.get('mapId'))
    color = request.GET.get('color')
    listzong = [{"category":"游戏专属图标","iconlist":[]},]
    for i in Icon.objects.filter(gid=9900+temval//100):
        listzong[-1]['iconlist'].append(i.img)
    classlist = Iconclass.objects.filter(color=color)
    for j in classlist:
        listzong.append({"category":j.title,"iconlist":[]})
        for i in Icon.objects.filter(iid__startswith=j.id):
            listzong[-1]['iconlist'].append(i.img)
    json_icon["data"] = {"list":listzong}
    return JsonResponse(json_icon)

#上传图片
def post_img(request):
    #目前采用这个方法  之后尝试django-qiniu-storage
    image = request.FILES.get('image',None)
    path='uploadimg/'+image.name
    print(path)
    destination = open(path,'wb+')
    for chunk in image.chunks():
        destination.write(chunk)
    destination.close()
    #path = default_storage.save('uploadimg/tem.jpg', ContentFile(image.read()))
    # print(path)
    imgurl=upload_img(path)
    os.remove(path)
    return JsonResponse({"code":0,"data":{"url":imgurl}})






#127.0.0.1:8000/search/point      搜索点
def search_point(request):
    mid = int(request.GET.get('mid'))
    kkeyword = request.GET.get('keyword')
    json_search = {"code":0}
    temp = Point.objects.filter(Q(id__startswith=mid) & (Q(title__contains=kkeyword) | Q(content__contains=kkeyword))).values('title','id')
    json_search["data"] = {"list":list(temp)}
    return JsonResponse(json_search)
